package com.beiding.jsonanalyzer.analyze;

public class Segment {

    public final SegmentType type;

    public final String name;

    public final Integer index;

    private final int hashCache;

    /**
     * 任意字符区段
     * 为了支持扁平化的区段
     * 形如 a['user.name']
     * name的表示格式
     * true 格式为 user['name']
     * false 格式为 user.name
     */
    public final boolean integral;


    private Segment(SegmentType segmentType, String name, Integer index, boolean integral,int hashCache) {
        this.type = segmentType;
        this.name = name;
        this.index = index;
        this.integral = integral;
        this.hashCache = hashCache;

    }

    public static Segment createName(String name, boolean integral) {
        return new Segment(SegmentType.NAME, name, null, integral, name.hashCode());
    }

    public static Segment createIndex(int index) {
        return new Segment(SegmentType.INDEX, null, index, true, new Integer(index).hashCode());
    }

    public static Segment createAny(boolean integral) {
        return new Segment(SegmentType.ANY, "*", null, integral, 0);
    }

    @Override
    public int hashCode() {
        return hashCache;
    }

    @Override
    public boolean equals(Object obj) {

        if (!(obj instanceof Segment)) {
            return false;
        }

        if (((Segment) obj).type != this.type) {
            return false;
        }
        if (type == SegmentType.INDEX) {
            return this.index.equals(((Segment) obj).index);
        } else {
            return this.name.equals(((Segment) obj).name);
        }
    }

    @Override
    public String toString() {
        if (type == SegmentType.INDEX) {
            return "[" + index + "]";
        } else {
            if (integral) {
                return "['" + name + "']";
            } else {
                return name;
            }
        }
    }


    public boolean isIndex() {
        return type == SegmentType.INDEX;
    }

    public boolean isName() {
        return type == SegmentType.NAME;
    }

    public boolean isAny() {
        return this.type == SegmentType.ANY;
    }

}
